package net.qiqbframework.commandhandling.inspection;


import net.qiqbframework.commandhandling.CommandMessage;
import net.qiqbframework.messaging.InterceptorChain;
import net.qiqbframework.messaging.MessageHandlerInterceptor;
import net.qiqbframework.messaging.annotation.MessageExecutableHandler;
import net.qiqbframework.messaging.annotation.InterceptorChainParameterResolverFactory;
import net.qiqbframework.messaging.task.MessageTask;

import javax.annotation.Nonnull;

public class AnnotatedCommandHandlerInterceptor<T> implements MessageHandlerInterceptor<CommandMessage<?>> {

    private final MessageExecutableHandler delegate;
    private final T target;


    public AnnotatedCommandHandlerInterceptor(MessageExecutableHandler delegate, T target) {
        this.delegate = delegate;
        this.target = target;
    }

    @Override
    public Object handle(@Nonnull MessageTask<? extends CommandMessage<?>> messageTask,
                         @Nonnull InterceptorChain interceptorChain)
            throws Exception {
        return InterceptorChainParameterResolverFactory.callWithInterceptorChain(
                interceptorChain,
                () -> delegate.canHandle(messageTask.getMessage())
                        ? delegate.handle(messageTask.getMessage(), target)
                        : interceptorChain.proceed());
    }
}
